
package com.ruhua.java.service;

import com.ruhua.java.core.LocalAdmin;
import com.ruhua.java.dao.Admin;
import com.ruhua.java.dto.TokenDTO;
import com.ruhua.java.exception.ErrException;
import com.ruhua.java.repository.AdminRepository;
import com.ruhua.java.util.CommonUtil;
import com.ruhua.java.util.JwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class TokenService {


    @Autowired
    AdminRepository adminRepository;



    public Map<String, String> CmsToken(String username,String psw) {
        String new_psw=CommonUtil.md5(psw);
        Map<String, String> map = new HashMap<>();
        Optional<Admin> oadmin= adminRepository.findNamePsw(username,new_psw);
        Admin admin=oadmin.orElseThrow(()-> new ErrException("账号或密码错误"));
        String token = JwtToken.makeToken(admin.getId(),12);map.put("token",token);
        return map;
    }


    public void editPsw(String psw,String old) {
        Long uid = LocalAdmin.getUser().getId();
        String old_psw=CommonUtil.md5(old);
        String new_psw=CommonUtil.md5(psw);
        Optional<Admin> item=adminRepository.findById(uid);
        Admin admin=item.orElseThrow(()->new ErrException("用户不存在"));
        if(!admin.getPassword().equals(old_psw)){
            throw new ErrException("原密码错误");
        }
        admin.setPassword(new_psw);
        adminRepository.save(admin);
    }

    public Map<String, Boolean> verify(@RequestBody TokenDTO token) {
        Map<String, Boolean> map = new HashMap<>();
        Boolean valid = JwtToken.verifyToken(token.getToken());
        map.put("is_valid", valid);
        return map;
    }
}

